// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace BlueOnionSoftware.Bloget
{
    internal class XmlRpcMethodCall
    {
        private readonly List<XmlRpcValue> parameters = new List<XmlRpcValue>();

        internal string Name { get; set; }

        internal XmlRpcValue[] Parameters
        {
            get { return parameters.ToArray(); }
        }

        internal void AddParam(XmlRpcValue param)
        {
            Throw.IfNull(param, "param");
            parameters.Add(param);
        }

        public override string ToString()
        {
            var xmlSettings = new XmlWriterSettings();
            xmlSettings.Encoding = new UTF8Encoding(false);

            using (var stream = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(stream, xmlSettings))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("methodCall");
                    writer.WriteElementString("methodName", Name);

                    foreach (var value in parameters)
                    {
                        value.Serialize(writer);
                    }

                    writer.WriteEndDocument();
                    writer.Flush();
                    return Encoding.UTF8.GetString(stream.ToArray());
                }
            }
        }
    }
}